package com.smart.translator.ui.voice;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.smart.translator.R;
import com.smart.translator.util.VoskSpeechRecognizer;
import android.widget.RadioGroup;
import android.widget.RadioButton;

/**
 * Vosk语音识别演示Activity
 */
public class VoskDemoActivity extends AppCompatActivity {
    private static final String TAG = "VoskDemoActivity";
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 1001;
    
    // UI组件
    private TextView tvStatus;
    private TextView tvResult;
    private TextView tvPartialResult;
    private Button btnLoadModel;
    private Button btnStartRecognition;
    private Button btnStopRecognition;
    private android.widget.ImageView btnBack;
    private RadioGroup rgAudioSource;
    private RadioButton rbMic;
    private RadioButton rbDefault;
    
    // Vosk语音识别器
    private VoskSpeechRecognizer voskRecognizer;
    
    // 模型路径
    private static final String MODEL_PATH = "vosk-model-cn-0.22";
    private static final String MODEL_ZIP_PATH = "vosk-model-cn-0.22.zip";
    private static final String SMALL_MODEL_PATH = "vosk-model-small-cn-0.22";
    private static final String SMALL_MODEL_ZIP_PATH = "vosk-model-small-cn-0.22.zip";
    private String currentModelPath;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vosk_demo);
        
        initViews();
        initVoskRecognizer();
        setupListeners();
        checkPermissions();
    }
    
    private void initViews() {
        tvStatus = findViewById(R.id.tv_status);
        tvResult = findViewById(R.id.tv_result);
        tvPartialResult = findViewById(R.id.tv_partial_result);
        btnLoadModel = findViewById(R.id.btn_load_model);
        btnStartRecognition = findViewById(R.id.btn_start_recognition);
        btnStopRecognition = findViewById(R.id.btn_stop_recognition);
        btnBack = findViewById(R.id.btn_back);
        
        // 初始化音频源选择组件
        rgAudioSource = findViewById(R.id.rg_audio_source);
        rbMic = findViewById(R.id.rb_mic);
        rbDefault = findViewById(R.id.rb_default);
        
        // 初始状态
        updateUI(false, false);
    }
    
    private void initVoskRecognizer() {
        voskRecognizer = new VoskSpeechRecognizer(this);
        voskRecognizer.setSpeechRecognitionListener(new VoskSpeechRecognizer.SpeechRecognitionListener() {
            @Override
            public void onResult(String result) {
                Log.d(TAG, "最终识别结果: " + result);
                runOnUiThread(() -> {
                    tvResult.setText("最终结果: " + result);
                    Toast.makeText(VoskDemoActivity.this, "识别完成: " + result, Toast.LENGTH_SHORT).show();
                });
            }
            
            @Override
            public void onPartialResult(String partialResult) {
                Log.d(TAG, "部分识别结果: " + partialResult);
                runOnUiThread(() -> {
                    tvPartialResult.setText("部分结果: " + partialResult);
                });
            }
            
            @Override
            public void onError(String error) {
                Log.e(TAG, "识别错误: " + error);
                runOnUiThread(() -> {
                    tvStatus.setText("状态: 错误 - " + error);
                    Toast.makeText(VoskDemoActivity.this, "错误: " + error, Toast.LENGTH_SHORT).show();
                    updateUI(voskRecognizer.isModelLoaded(), false);
                });
            }
            
            @Override
            public void onModelLoaded() {
                Log.d(TAG, "模型加载完成");
                runOnUiThread(() -> {
                    tvStatus.setText("状态: 模型已加载");
                    Toast.makeText(VoskDemoActivity.this, "模型加载成功", Toast.LENGTH_SHORT).show();
                    updateUI(true, false);
                });
            }
            
            @Override
            public void onModelLoadError(String error) {
                Log.e(TAG, "模型加载失败: " + error);
                runOnUiThread(() -> {
                    tvStatus.setText("状态: 模型加载失败");
                    Toast.makeText(VoskDemoActivity.this, "模型加载失败: " + error, Toast.LENGTH_SHORT).show();
                    updateUI(false, false);
                });
            }
        });
    }
    
    private void setupListeners() {
        btnBack.setOnClickListener(v -> finish());
        
        btnLoadModel.setOnClickListener(v -> {
            if (checkRecordAudioPermission()) {
                loadModel();
            } else {
                requestRecordAudioPermission();
            }
        });
        
        btnStartRecognition.setOnClickListener(v -> {
            if (checkRecordAudioPermission()) {
                startRecognition();
            } else {
                requestRecordAudioPermission();
            }
        });
        
        btnStopRecognition.setOnClickListener(v -> {
            stopRecognition();
        });
        
        // 音频源选择监听器
        rgAudioSource.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_mic) {
                voskRecognizer.setAudioSource(VoskSpeechRecognizer.AUDIO_SOURCE_MIC);
                Log.d(TAG, "选择音频源: 手机麦克风");
            } else if (checkedId == R.id.rb_default) {
                voskRecognizer.setAudioSource(VoskSpeechRecognizer.AUDIO_SOURCE_DEFAULT);
                Log.d(TAG, "选择音频源: 默认音频源");
            }
        });
    }
    
    private void loadModel() {
        // 直接加载完整模型
        performModelLoad();
    }
    
    private void showModelSelectionDialog() {
        // 暂时只提供完整模型选项
        String[] models = {"完整模型 (vosk-model-cn-0.22)"};
        
        new AlertDialog.Builder(this)
            .setTitle("选择语音识别模型")
            .setItems(models, (dialog, which) -> {
                Log.d(TAG, "选择模型: " + MODEL_PATH);
                performModelLoad();
            })
            .setNegativeButton("取消", (dialog, which) -> {
                btnLoadModel.setEnabled(true);
                tvStatus.setText("状态: 模型未加载");
            })
            .show();
    }
    
    private void performModelLoad() {
        tvStatus.setText("状态: 正在加载模型...");
        btnLoadModel.setEnabled(false);
        
        // 检测可用的模型文件
        try {
            String[] assets = getAssets().list("");
            boolean smallZipExists = false;
            boolean smallFolderExists = false;
            boolean fullZipExists = false;
            boolean fullFolderExists = false;
            
            for (String asset : assets) {
                if (asset.equals(SMALL_MODEL_ZIP_PATH)) {
                    smallZipExists = true;
                    Log.d(TAG, "找到小型模型zip文件: " + asset);
                } else if (asset.equals(SMALL_MODEL_PATH)) {
                    smallFolderExists = true;
                    Log.d(TAG, "找到小型模型文件夹: " + asset);
                } else if (asset.equals(MODEL_ZIP_PATH)) {
                    fullZipExists = true;
                    Log.d(TAG, "找到完整模型zip文件: " + asset);
                } else if (asset.equals(MODEL_PATH)) {
                    fullFolderExists = true;
                    Log.d(TAG, "找到完整模型文件夹: " + asset);
                }
            }
            
            // 优先使用小型模型以避免内存问题
            if (smallZipExists) {
                currentModelPath = SMALL_MODEL_ZIP_PATH;
                Log.d(TAG, "使用小型模型zip文件: " + currentModelPath);
            } else if (smallFolderExists) {
                currentModelPath = SMALL_MODEL_PATH;
                Log.d(TAG, "使用小型模型文件夹: " + currentModelPath);
            } else if (fullZipExists) {
                currentModelPath = MODEL_ZIP_PATH;
                Log.d(TAG, "使用完整模型zip文件: " + currentModelPath);
            } else if (fullFolderExists) {
                currentModelPath = MODEL_PATH;
                Log.d(TAG, "使用完整模型文件夹: " + currentModelPath);
            } else {
                Log.e(TAG, "未找到任何模型文件");
                showModelDownloadDialog();
                btnLoadModel.setEnabled(true);
                return;
            }
            
        } catch (Exception e) {
            Log.e(TAG, "检查模型文件失败", e);
            showModelDownloadDialog();
            btnLoadModel.setEnabled(true);
            return;
        }
        
        // 加载模型
        voskRecognizer.loadModel(currentModelPath);
    }
    
    private void startRecognition() {
        if (!voskRecognizer.isModelLoaded()) {
            Toast.makeText(this, "请先加载模型", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (voskRecognizer.isRecording()) {
            Toast.makeText(this, "识别已在运行中", Toast.LENGTH_SHORT).show();
            return;
        }
        
        String audioSourceName = voskRecognizer.getAudioSourceName();
        tvStatus.setText("状态: 正在识别... (" + audioSourceName + ")");
        tvResult.setText("最终结果: ");
        tvPartialResult.setText("部分结果: ");
        updateUI(true, true);
        
        Log.d(TAG, "开始语音识别，使用音频源: " + audioSourceName);
        voskRecognizer.startRecognition();
    }
    
    private void stopRecognition() {
        if (!voskRecognizer.isRecording()) {
            Toast.makeText(this, "识别未在运行", Toast.LENGTH_SHORT).show();
            return;
        }
        
        tvStatus.setText("状态: 正在停止...");
        voskRecognizer.stopRecognition();
        
        // 在用户主动停止时获取最终结果
        voskRecognizer.getFinalResult();
        
        updateUI(true, false);
    }
    
    private void updateUI(boolean modelLoaded, boolean isRecording) {
        btnLoadModel.setEnabled(!modelLoaded);
        btnStartRecognition.setEnabled(modelLoaded && !isRecording);
        btnStopRecognition.setEnabled(isRecording);
        
        if (!modelLoaded) {
            tvStatus.setText("状态: 模型未加载");
        } else if (isRecording) {
            tvStatus.setText("状态: 正在识别");
        } else {
            tvStatus.setText("状态: 就绪");
        }
    }
    
    private void showModelDownloadDialog() {
        new AlertDialog.Builder(this)
            .setTitle("模型文件未找到")
            .setMessage("需要下载Vosk语音识别模型文件。\n\n" +
                       "1. 访问 https://alphacephei.com/vosk/models\n" +
                       "2. 下载中文模型 vosk-model-cn-0.22\n" +
                       "3. 将zip文件放入 app/src/main/assets/ 目录\n" +
                       "4. 或者解压后将文件夹放入 app/src/main/assets/ 目录\n" +
                       "5. 重新运行应用")
            .setPositiveButton("确定", null)
            .setNegativeButton("取消", (dialog, which) -> {
                btnLoadModel.setEnabled(true);
                tvStatus.setText("状态: 模型未加载");
            })
            .show();
    }
    
    private boolean checkRecordAudioPermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) 
               == PackageManager.PERMISSION_GRANTED;
    }
    
    private void requestRecordAudioPermission() {
        ActivityCompat.requestPermissions(this, 
            new String[]{Manifest.permission.RECORD_AUDIO}, 
            REQUEST_RECORD_AUDIO_PERMISSION);
    }
    
    private void checkPermissions() {
        if (!checkRecordAudioPermission()) {
            requestRecordAudioPermission();
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, 
                                         @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "录音权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "需要录音权限才能使用语音识别功能", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "VoskDemoActivity onPause");
        
        // 如果正在录音，停止录音但不获取最终结果
        if (voskRecognizer != null && voskRecognizer.isRecording()) {
            Log.d(TAG, "Activity暂停，停止语音识别");
            voskRecognizer.stopRecognition();
            // 不在onPause时获取最终结果，避免崩溃
            updateUI(voskRecognizer.isModelLoaded(), false);
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "VoskDemoActivity onDestroy");
        
        try {
            if (voskRecognizer != null) {
                Log.d(TAG, "释放VoskSpeechRecognizer资源");
                voskRecognizer.release();
                voskRecognizer = null;
            }
        } catch (Exception e) {
            Log.e(TAG, "释放VoskSpeechRecognizer资源时发生错误", e);
        }
        
        Log.d(TAG, "VoskDemoActivity资源已释放");
    }
} 